package com.lcp.se.service;

import com.alibaba.fastjson.JSONObject;
import com.lcp.se.entity.data.Chat;
import com.lcp.se.entity.data.VideoCall;
import com.lcp.se.entity.result.Message;
import com.lcp.se.entity.vo.AppointmentVO;
import com.lcp.se.util.MessageProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 向 RabbitMQ 发送消息
 * <p>
 *
 * @author lcp
 * @date 2020/7/24 16:03
 */
@Service
public class AmqpMessageService {
    private final Logger log = LoggerFactory.getLogger(AmqpMessageService.class);

    @Value("${mini-program.socket-info-key-redis}")
    private String socketInfoKey;

    @Value("${mini-program.msg-exchange-name}")
    private String exchangeName;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    public <T> void sendMessage(Message<T> message, String toUserOpenId) {
        Object routingkey = redisTemplate.opsForHash().get(socketInfoKey, toUserOpenId);
        if (Objects.isNull(routingkey)) {
            return;
        }
        log.info("发送" + message);
        send(routingkey.toString(), message.getData(), MessageProperty.MSG_APPOINTMENT_ACCEPTED);
    }

    public void sendMessage(Chat chat) {
        String toUserOpenId = chat.getToUserOpenId();
        Object routingkey = redisTemplate.opsForHash().get(socketInfoKey, toUserOpenId);
        if (Objects.isNull(routingkey)) {
            return;
        }
        send(routingkey.toString(), chat, MessageProperty.MSG_CHAT);
    }

    public void sendMessage(AppointmentVO appointment) {
        send("im", appointment, MessageProperty.MSG_APPOINTMENT);
    }

    public void sendMessage(VideoCall videoCall) {
        send("im", videoCall, MessageProperty.MSG_VIDEO_CALL);
    }

    public <T> void send(String routingKey, T data, String msgProperty) {
        JSONObject msg = new JSONObject();
        msg.put(MessageProperty.KEY_MESSAGE_PROPERTY, msgProperty);
        msg.put(MessageProperty.KEY_DATA, data);
        rabbitTemplate.convertAndSend(exchangeName, routingKey, msg);
    }
}
